<?php

namespace addons\facrm\controller\facrm\setting;

use addons\facrm\library\BackendApi;

use think\Exception;


/**
 * 云呼管理
 * @icon fa fa-tags
 */
class Cloudcall extends BackendApi
{

    protected $key = "cloudcall";
    protected $addon_config = array();
    protected $data_temp = array();
	protected $noNeedRight = ['setup'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\facrm\Setting();
    }

    /**
     * 云呼叫
     * @ApiMethod (POST|GET)
     * @ApiParams(name="type", type="string", required=true, description="customer客户,customer_contacts联系人,clues线索,")
     * @ApiParams(name="typeid", type="int", required=true, description="对应的ID")
     * @ApiParams(name="field", type="string", required=flase, description="拨打电话对应的字段如手机号mobile，电话telephone。默认是mobile")
     * @ApiParams(name="prefix", type="string", required=flase, description="拨打电话前缀，可留空")
     * @ApiParams(name="name", type="string", required=flase, description="联系人名称")
     * @return string
     * @throws Exception
     */
    public function call(){

        $typeid = $this->request->request('typeid', 0,'intval');
        $type = $this->request->request('type', "customer");
        $field = $this->request->request('field', "mobile");
        $prefix = $this->request->request('prefix', "");
        $name=$this->request->request('name');


        if (!$typeid||!$type||!$field) $this->error(__("参数有误"));
        try {
            //获取号码
            switch ($type) {
                case 'customer':
                    $this->model = new \app\admin\model\facrm\Customer();
                    break;
                case 'customer_contacts':
                    $this->model = new \app\admin\model\facrm\customer\Contacts();
                    break;
                default:
                    $this->model = model('\app\admin\model\facrm\\' . ucfirst($type));
                    break;
            }
            $mobile=$this->model->where('id',$typeid)->value($field);
            if (!$mobile) $this->error(__("联系方式不存在"));
            //获取云呼配置
            $all_types =  \addons\facrm\library\cloudcall\Call::getProviders();
            $keys = "";
            foreach ($all_types as $v) {
                $keys .= $keys ? ',' . $this->key. $v : $this->key . $v;
            }
            $settingModel = new \app\admin\model\facrm\Setting();
            $setting= $settingModel->where('key', 'in', $keys)->where('status', 1)->find();//只找一条云呼通道

            if (!$setting) {
                $this->error(__("云呼通道没有配置，请先配置"));
            }
            //获取坐席
            $cloudcallModel = new \app\admin\model\facrm\Cloudcall();
            $callrow=$cloudcallModel->where('admin_id',$this->auth->id)->where('cloud',$setting->describe)->where('status',1)->find();

            if (!$callrow) $this->error(__("您当前账号没有配置坐席"));
            $setting=$setting->toArray();
            $setting['key']=$setting['describe'];
            $setting=array_merge($setting,$setting['values']);
            $call= \addons\facrm\library\cloudcall\Call::instance($setting);

            $data['exten']=$mobile;
            $data['from_exten']=$callrow['from_exten'];
            $data['exten_type']=$callrow['exten_type'];

            $result=$call->call($data,$callrow);
            if (!$result){
                $this->error($call->getError());
            }


            //成功拨打钩子
            hook('cloudcall_success', ['typeid' => $typeid, 'type' => $type,'name'=>$name, 'data' => $data, 'callrow' => $callrow]);

            //保存通话记录
            $cloudcallLog=new \app\admin\model\facrm\CloudcallLog();

            $cloudcallLog->isUpdate(false)->save([
                'admin_id'=>$this->auth->id,
                'cloud'=>$callrow['cloud'],
                'from_exten'=>$callrow['from_exten'],
                'exten_type'=>$data['exten_type'],
                'name'=>$name,
                'source'=>$type,
                'source_id'=>$typeid,
                'status'=>0,
                'call_no'=>'',
                'called_no'=>$mobile,
                'action_id'=>$result['ActionID'],
            ]);
            $this->success(__("呼叫成功"));

        }catch (Exception $e){
            $this->error($e->getMessage());
        }
        $this->error();
    }

    /**
     * 设置呼叫方式
     * @ApiMethod (POST|GET)
     * @ApiParams(name="exten_type", type="string", required=flase, description="云呼方式，POST才需要")
     * @ApiBody ("POST是提交修改，GET获取数据")
     */
	public function setup(){
		$extentype_arr=['local'=>'工作手机','sip'=>'软电话','gateway'=>'话机方式'];
		//获取云呼配置
		$all_types =  \addons\facrm\library\cloudcall\Call::getProviders();
		$keys = "";
		foreach ($all_types as $v) {
			$keys .= $keys ? ',' . $this->key. $v : $this->key . $v;
		}
		$settingModel = new \app\admin\model\facrm\Setting();
		$setting= $settingModel->where('key', 'in', $keys)->where('status', 1)->find();//只找一条云呼通道
		if (!$setting) {
			$this->error(__("云呼通道没有配置，请先配置"));
        }
		//获取坐席
		$cloudcallModel = new \app\admin\model\facrm\Cloudcall();
		$callrow=$cloudcallModel->where('admin_id',$this->auth->id)->where('cloud',$setting->describe)->where('status',1)->find();
		if(!$callrow) {
			$this->error(__("当前账号尚未配置坐席，请在PC配置坐席"));
        }
		 if ($this->request->isPost()) {
			 $exten_type = $this->request->request('exten_type');
			 if(!in_array($exten_type,array_keys($extentype_arr))){
				 $this->error(__("参数有误"));
			 }
			
			 $callrow->exten_type=$exten_type;
			 $callrow->save();
            $this->success('设置成功');
        }
		$this->success('',['extentype'=>$extentype_arr,'callrow'=>$callrow]);
	}


}